<template>
	<div class="modifyGoodsBox" v-loading="loading">
		<el-form ref="form">
			<el-form-item label="商品名称">
				<el-input v-model="initial_data.name" style="width:300px"></el-input>
			</el-form-item>

			<el-form-item label="商品简介">
				<el-input v-model="initial_data.slogan" style="width:300px"></el-input>
			</el-form-item>

			<el-form-item label="商户状态">
				<el-select style="width: 300px" v-model="initial_data.status" placeholder="请选择商户状态">
					<el-option
						v-for="(item) in statusOption"
						:label="item.name"
						:value="item.id"
						:key="item.id"
					></el-option>
				</el-select>
			</el-form-item>


			<el-form-item label="出价">
				<el-input v-model="initial_data.selling_price" style="width:300px"></el-input>
			</el-form-item>

			<el-form-item label="进价">
				<el-input v-model="initial_data.purchase_price" style="width:300px"></el-input>
			</el-form-item>

			<el-form-item label="原价">
				<el-input v-model="initial_data.original_price" style="width:300px"></el-input>
			</el-form-item>

			<el-form-item label="销量">
				<el-input v-model="initial_data.sales_volume" style="width:300px"></el-input>
			</el-form-item>

			<el-form-item label="库存">
				<el-input v-model="initial_data.stock" style="width:300px"></el-input>
			</el-form-item>

			<el-form-item label="分类名称">
				<el-select v-model="initial_data.classify_id" placeholder="请选择分类名称">
					<el-option v-for="(item) in classifyList" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>

		</el-form>

		<!-- 编辑器 -->
		<div class="pictures">
			<span class="title">商品详情</span>
			<div class="editorBox">
			  <div id="toorbar" class="toolbar">
			  </div>
			  <div></div>
			  <div id="editBox" class="editBox">
				  <div v-html="initial_data.detail"></div>
			  </div>
			</div>
		</div>



		<div class="pictures">
			<span class="title">商品缩略图</span>
			<div class="picUpload">
				<div>
					<el-upload
						:http-request="handlePictureCardPreview"
						:multiple="false"
						action=""
						name="business_thumbnails"
						list-type="picture-card"
					>
						<i class="el-icon-plus"></i>
					</el-upload>
					<el-dialog
						:modal="false"
						:center="true"
						:show-close="false"
						class="commonVisible"
						:visible.sync="businesstThumbnailsVisible"
						:fullscreen="true">
						<img  alt="" class="" :src="initial_data.thumbnail" v-show="businesstThumbnailsVisible">
						<span class="hoverBox" @click="businesstThumbnailsVisible=false" v-show="businesstThumbnailsVisible" >
							<span class="deleteIcon">
								<i class="el-icon-delete" @click="thumbnailDelete"></i>
							</span>
						</span>
					</el-dialog>
				</div>
			</div>
		</div>

		<div class="pictures">
			<span class="title">商品图片</span>
			<div class="picUpload" :key="index" v-for="(item,index) in initial_data.images">
				<div>
					<el-upload
						:http-request="handlePictureCardPreview"
						:multiple="false"
						action=""
						name="goods_picture"
						list-type="picture-card"
					>
						<i class="el-icon-plus"></i>
					</el-upload>
                    <el-dialog
                            :modal="false"
                            :center="true"
                            :show-close="false"
                            class="commonVisible"
                            :visible.sync="item.thumbnailsVisible"
                            :fullscreen="true">
                        <img  alt="" class="" :src="item.image" v-show="item.thumbnailsVisible">
                        <span class="hoverBox" @click="deleteImages(item,index)" v-show="item.thumbnailsVisible">
							<span class="deleteIcon">
								<i class="el-icon-delete" @click="imagesDelete(item,index)"></i>
							</span>
						</span>
                    </el-dialog>
				</div>
			</div>
		</div>

        <div class="pictures">
            <span class="title">团购</span>
            <div style="margin-top: 10px">
                <el-switch
                        @change="changeGroupBy"
                        style="display: block"
                        v-model="initial_data.is_group"
                        active-text="参与"
                        inactive-text="不参与">
                </el-switch>
            </div>
        </div>

        <div class="pictures" v-if="groupVisible">
            <span class="title">团购人数</span>
            <el-input v-model="initial_data.people" style="width:300px">
            </el-input>
        </div>

        <div class="pictures">
            <span class="title">秒杀</span>
            <div style="margin-top: 10px">
                <el-switch
                        @change="changeSpike"
                        style="display: block"
                        v-model="initial_data.is_spike"
                        active-text="参与"
                        inactive-text="不参与">
                </el-switch>
            </div>
        </div>

        <div class="pictures" v-if="spikeVisible">
            <span class="title">秒杀价格</span>
            <el-input v-model="initial_data.spike_selling_price" style="width:300px">
            </el-input>
        </div>

        <div class="pictures" v-if="spikeVisible">
            <span class="title">秒杀日期</span>
            <el-date-picker
                    v-model="initial_data.day"
                    value-format="yyyy-MM-dd"
                    style="width:400px"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
        </div>

        <div class="pictures" v-if="spikeVisible">
            <span class="title">秒杀时间</span>
            <el-select  multiple style="width: 300px" v-model="initial_data.hour" placeholder="请选择">
                <el-option

                        v-for="item in spikeTime"
                        :key="item.name"
                        :label="item.name"
                        :value="item.name">
                </el-option>
            </el-select>
        </div>

		<shelfGoods v-if="getskuData"
                    :skuData = "getskuData"
                    :enable_sku = "initial_data.enable_sku"
                    @setSkuData="setSkuData">
        </shelfGoods>

		<div class="submitBtnBox">
			<el-button class="submitBtn" @click="submitFn" type="primary">确认修改</el-button>
		</div>

	</div>
</template>

<script>
import E from 'wangeditor'
import shelfGoods from '@/layout/components/shelf-goods'
var editor = new E('#toorbar','#editBox');
const _ = require('lodash');
export default {
	name: 'Modify-goods',
	components: { shelfGoods },
	data() {
		return {
			loading: false,
			list:null,
			businesstThumbnailsVisible:true,
			classifyList:[],
			statusOption:[
			{
				id:1,
				name:'下架'
			},
			{
				id:2,
				name:'上架'
			}],
			getskuData:'',
			initial_data:'',//获取初始数据
			sku_data:[],
			sku:[],
            spikeVisible: true,
            groupVisible: true,
            spikeTime: [
                {id: 1, name: '00:00'},
                {id: 2, name: '06:00'},
                {id: 3, name: '08:00'},
                {id: 4, name: '10:00'},
                {id: 5, name: '12:00'},
            ],
            images: []
		}
	},
	watch:{

	},
	computed:{
		submitObj(){
			return {
				token:localStorage.getItem('user_token'),//token
				id:this.$route.query.id,//商品id
				name:this.initial_data.name,//商品名称
				slogan:this.initial_data.slogan,//商品简介
				thumbnail:this.initial_data.thumbnail,//商品缩略图
				selling_price:this.initial_data.selling_price,//售价
				purchase_price:this.initial_data.purchase_price,//进价
				original_price:this.initial_data.original_price,//原价
				sales_volume:this.initial_data.sales_volume,//销量
				detail:this.initial_data.detail,//富文本编辑器
				// sort:this.initial_data.sort,//排序
				classify_id:this.initial_data.classify_id,//分类名称
				status:this.initial_data.status,//商户状态
				stock:this.initial_data.stock,//库存
				images:this.initial_data.images,//商品图片
				sku_data:this.sku_data,//规格项
				sku:this.sku,//商品规格表格内容
                enable_sku: this.initial_data.enable_sku,
			}
		}
	},

	methods: {
        deleteImages(value,key){
            this.initial_data.images.splice(key,1)
            console.log(this.initial_data.images,key)
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },

		defalutFn(){//初始化数据
			this.loading = true;
			this.$http.get('/web/good/read', {
				params:{
					'token': localStorage.getItem('user_token'),
					'id': this.$route.query.id
				}
			}).then((response)=>{
				if(response.data.status === 'success'){
				    this.groupVisible = response.data.data.is_group;
                    this.spikeVisible = response.data.data.is_spike;
					this.initial_data = response.data.data;
					this.getskuData = this.initial_data.sku;
					this.initial_data.images.forEach((val,index) => {
					   this.$set(this.initial_data.images[index],'thumbnailsVisible',true);
					})

					this.loading=false;
				}
			}).catch((error)=>{
				this.loading=false;
			})

		},
		getClassifyFn(){//分类列表
			this.$http.post('/web/good/classify', {
				'token': localStorage.getItem('user_token'),
				'p_id':this.$route.query.id
			}).then((response)=>{
				if(response.data.status == 'success'){
					this.classifyList = response.data.data;
				}
			}).catch((error)=>{
				console.log('error:',error)
			})
		},
		handlePictureCardPreview(file){//图片上传
			console.log('file-file:',file.filename);
			let imageFile = file.file;
			let formData = new FormData();

			formData.append("image", imageFile);
			formData.append("action", file.filename);
			this.loading = true;
			this.$http.post('/api/tool/ali/upload/image',formData).then((response)=>{
				if(file.filename === 'business_thumbnails'){//商户缩略图
					this.initial_data.thumbnail = response.data.data;
				}
				if(file.filename === 'goods_picture'){//商品图片
					this.images.push(response.data.data)
				}
				this.loading = false;
			}).catch((error)=>{
				console.log('图片上传失败');
			})
		},
		submitFn(){
		    if (this.submitObj.sku){
                this.submitObj.sku = JSON.stringify(this.submitObj.sku)
            }
            if (this.submitObj.sku_data){
                this.submitObj.sku_data = JSON.stringify(this.submitObj.sku_data)
            }
            this.$http.post('/web/good/update', this.submitObj).then((response)=>{
				console.log('response:',response)
				if(response.data.status === 'success'){

				}
			}).catch((error)=>{
				console.log('error:',error)
			})
		},
		setSkuData(val){
			// sku_data
			let sku_data = [];
			val.levelcont.forEach((value,index) => {
				let arr_cont = [];
				let arr_thumbnail = [];
				val.levellist[index].forEach((vallist,indexlist) => {
					arr_cont.push(vallist.cont);
					arr_thumbnail.push(vallist.thumbnail);
				})
				sku_data.push({
					'sku':value,
					'name':arr_cont,
					'thumbnail':arr_thumbnail
				})
			})
			this.sku_data = sku_data;

			// sku
			if(val.finalData){
				let sku = [];
				let sku_length = this.sku_data.length;
				let sku_value = [];
				val.finalData.forEach((valuesku,indexsku) => {
					sku_value.push({
						'value':_.take(valuesku,sku_length),
						'purchase_price':_.takeRight(valuesku,4)[0],
						'original_price':_.takeRight(valuesku,4)[1],
						'selling_price':_.takeRight(valuesku,4)[2],
						'stock':_.takeRight(valuesku,4)[3]
					})

				})
				this.sku = sku_value;
			}


		},
		editorFn(){

		  editor.customConfig.onchange = (html) => {
			editor.txt.clear();
			editor.txt.html(html);
			this.initial_data.detail = html;
		  }

		  // 自定义菜单配置
		  editor.customConfig.menus = [
		      'head',  // 标题
		      'bold',  // 粗体
		      'fontSize',  // 字号
		      'fontName',  // 字体
		      'underline',  // 下划线
		      'strikeThrough',  // 删除线
		      'foreColor',  // 文字颜色
		      'backColor',  // 背景颜色
		      'link',  // 插入链接
		      'list',  // 列表
		      'justify',  // 对齐方式
		      'image',  // 插入图片
		      'table',  // 表格
		      'undo',  // 撤销
		  ]

		  editor.customConfig.zIndex = 100;
		  editor.customConfig.uploadImgShowBase64 = true
		  editor.customConfig.showLinkImg = false

		  //获取焦点
		  var that=this;
		  editor.create();
		},
		thumbnailDelete(){
			// console.log('缩略图删除');
			this.initial_data.thumbnail = '';
		},
		imagesDelete(val,index){
			// console.log('商品图片删除');
			this.initial_data.images[index].image = '';
		},
        changeGroupBy(value) {
            this.groupVisible = value;
        },

        changeSpike(value) {
            this.spikeVisible = value;
        },
	},
	mounted(){
		this.defalutFn();
		this.getClassifyFn();
		this.editorFn();
	}
}
</script>

<style scoped lang="scss">
	.submitBtnBox{
		text-align:right;
		margin-top:30px;
	}
	.editorBox{
		width:800px;
		border:1px solid #ccc;
		.toolbar{
			background-color:#f7f6f6;
		}
		.editBox{
			height:300px;
		}
	}
	.modifyGoodsBox{
		min-width:1024px;
		margin:40px;
		/deep/ .el-form-item__label{
			width:100px;
			text-align:left;
		}

		.pictures{
			display:flex;
			flex-direction:row;
			font-size:14px;
			color:#606266;
			line-height:40px;
			font-weight:700;
			margin-bottom:30px;
			.title{
				width:100px;
			}
		}
		.picUpload{
			position:relative;
			margin-right:20px;
			width:148px;
			/deep/ .el-dialog{
				box-shadow:none
			}
			/deep/.el-upload-list__item{
				position:absolute;
				z-index:4;
			}
			/deep/ .el-dialog__header,/deep/.el-dialog__body{
				padding:0
			}
			/deep/ .el-dialog.is-fullscreen{
				height:148px;
			}
			/deep/.el-dialog__body{
				display:flex;
				align-items:center;
			}
			.title{
				text-align:center;
				width:100%;
				display:block;
				margin-top:20px;
			}
			.commonVisible{
				position:absolute;
				left:0;
				top:0;
				width:100%;
				height:100%;
				overflow:hidden;

				/deep/ .el-dialog__body{
					display:flex;
					align-items:center;
					height:100%;
					img{
						width:100%;
						display:block;
					}
				}
			}

			/deep/ .hoverBox{
				position: absolute;
				width: 100%;
				height: 100%;
				left: 0;
				top: 0;
				cursor: default;
				text-align: center;
				color: #fff;
				opacity: 1;
				font-size: 20px;
				background-color: rgba(0,0,0,.5);
				opacity:0;
				// -webkit-transition: opacity .3s;
				// transition: opacity .3s;
				&:hover{
					opacity:1
				}
				/deep/ .deleteIcon{
					display:flex;
					justify-content:center;
					align-items:center;
					height:100%;
				}
			}
		}


	}
</style>



